<template>
  <view class="container">
    <button @getuserinfo="userInfoCallBack" open-type="getUserInfo">请授权登录</button>
  </view>
</template>

<script>
import http from "../utils/http";
export default {
  data() {
    return {};
  },
  methods: {
    // 获取用户信息
    async userInfoCallBack(e) {
      const { encryptedData, rawData, iv, signature, userInfo } = e.detail;
      const [error, res] = await uni.login();
      const { code } = res;
      //  如果用户取消登录授权
      if (!encryptedData) {
        uni.showToast({
          title: "用户拒绝授权",
          icon: "none"
        });
        return;
      }
      // 请求自己服务端登录接口
      const data = await http.post("/users/wxlogin", {
        encryptedData,
        rawData,
        iv,
        signature,
        code
      });
      // console.log(data);
      // 将token存到本队存储
      uni.setStorage({
        key: "token",
        data: data.token
      });
      // 将个人信息存到本地存储
      uni.setStorage({
        key: "userInfo",
        data: userInfo
      });
      uni.showToast({
        title: "登录成功"
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1000);
    }
  }
};
</script>

<style lang="less" scoped>
.container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  button {
    background: #07c160;
    color: #fff;
  }
}
</style>